package com.yun.algorithmproblem.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Leetcode535_TinyURL {
    static public class Codec {
        private Map<String,String> longToShort=new HashMap<>();
        private Map<String,String> shortToLong=new HashMap<>();
        private static final String SHORT_PREFIX="http://tinyurl.com/";

        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            String shortUrl = longToShort.get(longUrl);
            if(shortUrl!=null){
                return shortUrl;
            }
            int id = longUrl.hashCode();//int
            while (true){
                //生成短网址
                //int id = ThreadLocalRandom.current().nextInt();//int
                shortUrl=SHORT_PREFIX+id;
                if(!shortToLong.containsKey(shortUrl)){
                    longToShort.put(longUrl,shortUrl);
                    shortToLong.put(shortUrl,longUrl);
                    break;
                }
                id++;
            }
            return shortUrl;
        }

        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return shortToLong.get(shortUrl);
        }
    }
}
